package us.ohec.validators {
  import us.ohec.utils.NumberUtil;
  
  import mx.validators.ValidationResult;
  import mx.validators.Validator;

  public class ACNValidator extends Validator {
    override protected function doValidation(value:Object): Array {
      var results:Array = super.doValidation(value);

      var val:String = value ? String(value) : "";

      if (results.length > 0 || ((val.length == 0) && ! required)) {
        return results;
      } else {
        return ACNValidator.validateACN(val);
      }
    }

    public static function validateACN(value:String): Array {
      var results:Array = [];

      value = NumberUtil.trim(value).toString();

      if (value.length != 9) {
        results.push(new ValidationResult(true, null, "invalidLength", "Invalid ACN length."));
        return results;
      }

      var acc:int = 0;

      for (var i:int = 0; i < 8; i++) {
        acc += Number(value.charAt(i)) * (8 - i);
      }
      acc = (10 - (acc % 10));

      if (Number(value.charAt(8)) != acc) {
        results.push(new ValidationResult(true, null, "invalidLength", "Invalid australian company number."));
      }

      return results;
    }
  }
}